<script setup lang="ts">
  import { useGetRegisterCodeList } from '@/services/pages/code'
  import { useGetGoods } from '@/services/pages/order/create'
  import { nextTick, PropType, ref, watch } from 'vue'
  import snCodeList from './sn-code-list.vue'
  import GoodList from './good-list.vue'
  import { Good } from '../../types'

  const { getGoodsParam, resetGetGoodsParam } = useGetGoods()
  const { getRegisteredCodeListParam, resetParam } = useGetRegisterCodeList()

  defineOptions({
    name: 'RepairGoodSelectModal',
  })

  const props = defineProps({
    userId: {
      type: String,
      required: true,
    },
    selectedList: {
      type: Array as PropType<Array<Good>>,
      default: () => [],
    },
  })

  const emits = defineEmits<{
    (e: 'update', value: Array<Good>): void
  }>()

  const visible = defineModel<boolean>('modelValue', { default: false })
  const activeName = ref<'snCode' | 'goodList'>('snCode')
  const snCodeListInstance = ref<InstanceType<typeof snCodeList> | null>(null)
  const goodListInstance = ref<InstanceType<typeof GoodList> | null>(null)
  const selection = ref<Array<Good>>([])

  const getList = () => {
    nextTick(() => {
      if (activeName.value === 'snCode' && snCodeListInstance.value) {
        resetParam()
        snCodeListInstance.value.getList()
      }

      if (activeName.value === 'goodList' && goodListInstance.value) {
        resetGetGoodsParam()
        goodListInstance.value.getList()
        goodListInstance.value.getGoodTypeOptionList()
      }
    })
  }

  const onResetClick = () => {
    if (activeName.value === 'snCode' && snCodeListInstance.value) {
      snCodeListInstance.value.getList()
    }

    if (activeName.value === 'goodList' && goodListInstance.value) {
      goodListInstance.value.getList()
      goodListInstance.value.getGoodTypeOptionList()
    }
  }

  const init = () => {
    getList()
    selection.value = props.selectedList
  }

  const handleGoodListSelectGood = (data: Array<OrderGood>) => {
    selection.value = selection.value.filter((item) => !!item.snCode)
    const selectionGoodIds = selection.value.map((item) => item.goodId)
    const selectionGoodSpecIds = selection.value.map((item) => item.goodSpecId)
    data.forEach((item) => {
      if (!selectionGoodIds.includes(item.id) || !selectionGoodSpecIds.includes(item.specId)) {
        selection.value.push({
          snCode: '',
          goodType: item.type,
          goodBrand: item.brand,
          goodId: item.id,
          goodSpecId: item.specId,
          goodCode: item.code,
          goodName: item.name,
          goodSpec: item.specName,
          qty: 1,
          warrantyStart: '',
          warrantyEnd: '',
          returnFactoryDesc: '',
          returnFactoryPictureList: [],
          repairVideoList: [],
          type: 1,
          isFixed: false,
        })
      }
    })
  }

  const handleSnCodeListSelectSnCode = (data: Array<CodeRegisteredCodeList>) => {
    selection.value = selection.value.filter((item) => !item.snCode)
    const selectionGoodIds = selection.value.map((item) => item.goodId)
    const selectionGoodSpecIds = selection.value.map((item) => item.goodSpecId)
    const selectionSnCodes = selection.value
      .filter((item) => !!item.snCode)
      .map((item) => item.snCode)
    data.forEach((item) => {
      if (
        !selectionGoodIds.includes(item.goodsId) ||
        !selectionGoodSpecIds.includes(item.goodsSpecId) ||
        !selectionSnCodes.includes(item.code)
      ) {
        selection.value.push({
          snCode: item.code,
          goodType: item.goodsType,
          goodBrand: item.goodsBrand,
          goodId: item.goodsId,
          goodSpecId: item.goodsSpecId,
          goodCode: item.goodsCode || '',
          goodName: item.goodsName,
          goodSpec: item.goodsSpecName,
          qty: 1,
          warrantyStart: item.warrantyStartTime,
          warrantyEnd: item.warrantyEndTime,
          returnFactoryDesc: '',
          returnFactoryPictureList: [],
          repairVideoList: [],
          type: 1,
          isFixed: false,
        })
      }
    })
  }

  const onConfirmClick = () => {
    emits('update', selection.value)
    visible.value = false
  }

  watch(visible, (value) => {
    value && init()
  })
</script>

<template>
  <h-drawer v-model="visible" title="选择产品" :width="1000" unit="px">
    <div class="tabs-wrapper">
      <div class="tabs-header">
        <el-tabs v-model="activeName" @tab-change="getList">
          <el-tab-pane label="选择条码" name="snCode" />
          <el-tab-pane label="产品列表" name="goodList" />
        </el-tabs>

        <template v-if="activeName === 'snCode'">
          <div class="header">
            <!-- 输入条码查询 -->
            <el-input
              v-model.trim="getRegisteredCodeListParam.code"
              placeholder="输入条码查询"
              style="width: 120px"
              clearable
              @clear="getList"
              @keyup.enter="getList"
            />

            <!-- 输入产品编号查询 -->
            <el-input
              v-model.trim="getRegisteredCodeListParam.goodsCode"
              placeholder="输入产品编号查询"
              style="width: 140px"
              clearable
              @clear="getList"
              @keyup.enter="getList"
            />

            <h-button type="primary" @click="getList">
              <el-icon>
                <Search></Search>
              </el-icon>
              搜索
            </h-button>

            <h-button @click="onResetClick">
              <el-icon>
                <RefreshRight></RefreshRight>
              </el-icon>
              取消
            </h-button>
          </div>
        </template>

        <template v-if="activeName === 'goodList'">
          <div class="header">
            <el-input
              v-model.trim="getGoodsParam.name"
              clearable
              placeholder="产品编号"
              style="width: 120px"
              @clear="getList"
              @keyup.enter="getList"
            />
            <el-input
              v-model.trim="getGoodsParam.model"
              clearable
              placeholder="产品名称"
              style="width: 120px"
              @clear="getList"
              @keyup.enter="getList"
            />
            <el-input
              v-model.trim="getGoodsParam.specs"
              clearable
              placeholder="产品规格"
              style="width: 120px"
              @clear="getList"
              @keyup.enter="getList"
            />
            <HButton type="primary" @click="getList">
              <el-icon>
                <Search />
              </el-icon>
              搜索
            </HButton>
            <HButton style="margin: 0" @click="onResetClick">
              <el-icon>
                <RefreshRight />
              </el-icon>
              重置
            </HButton>
          </div>
        </template>
      </div>
      <div class="tabs-content">
        <sn-code-list
          v-if="activeName === 'snCode'"
          ref="snCodeListInstance"
          :get-list-param="getRegisteredCodeListParam"
          :user-id="props.userId"
          :selected-list="props.selectedList"
          @select-sn-code="handleSnCodeListSelectSnCode"
        />
        <good-list
          v-if="activeName === 'goodList'"
          ref="goodListInstance"
          :get-list-param="getGoodsParam"
          :selected-list="props.selectedList"
          @select-good="handleGoodListSelectGood"
        />
      </div>
    </div>
    <template #footer>
      <h-button is-modal type="primary" @click="onConfirmClick">确定</h-button>
      <h-button is-modal @click="visible = false">取消</h-button>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  .tabs-wrapper {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    row-gap: 12px;

    .tabs-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #dcdfe6;
      padding: 0 8px;

      :deep(.el-tabs) {
        .el-tabs__header {
          margin: 0;

          .el-tabs__nav-wrap {
            &::after {
              display: none !important;
            }
          }
        }
      }

      .header {
        display: flex;
        column-gap: 5px;

        :deep(.el-select) {
          width: 140px;
        }

        :deep(.el-input) {
          width: 200px;
        }
      }
    }

    .tabs-content {
      flex: 1;
      height: 0;
    }
  }
</style>
